<template>
  <template v-if="loaded">
    <ProForm
      ref="formRef"
      :model="formState"
      :items="items"
      :disabled="readonly"
      :onValuesChange="onValuesChange"
      :formColLayout="formColLayout()"
      :requiredMark="!readonly"
      class="pro-form-modal"
      v-bind="formProps"
    >
    </ProForm>
    <FooterButtons
      :formState="formState"
      :formRef="formRef"
      v-model:readonly="readonly"
      :serviceApi="updateFileConfig"
      @refresh="refresh"
      :fastConfig="fastConfig"
    >
      <b-button @click="historyVisible = true">历史配置</b-button>
    </FooterButtons>

    <Modal
      title="历史配置"
      v-model:open="historyVisible"
      :width="1400"
      :mask-closable="false"
      :keyboard="false"
      :footer="null"
      centered
    >
      <ProTable
        ref="tableRef"
        :fetchListApi="_historyFile"
        :columns="columns"
        :height="600"
        row-key="id"
        hide-search
        :expanded-row-keys="expandedRowKeys"
        @expand="handleExpand"
      >
        <template #operation="{ record }">
          <b-button type="link" @click="File_deploy(record)">下发配置</b-button>
        </template>
        <template #expandedRowRender="{ record }">
          <Descriptions :column="4" style="padding: 15px 0 0 20px">
            <DescriptionsItem label="服务地址">{{
              record.data.fileServerIp
            }}</DescriptionsItem>
            <DescriptionsItem label="服务端口">{{
              record.data.fileServerPort
            }}</DescriptionsItem>
            <DescriptionsItem label="AccessKey">{{
              record.data.fileAccessKey
            }}</DescriptionsItem>
            <DescriptionsItem label="SecretKey">{{
              record.data.fileSecretKey
            }}</DescriptionsItem>
            <DescriptionsItem label="BucketName">{{
              record.data.fileBucketName
            }}</DescriptionsItem>
            <DescriptionsItem label="服务地址">{{
              record.data.ftpServerIp
            }}</DescriptionsItem>
            <DescriptionsItem label="服务端口">{{
              record.data.ftpServerPort
            }}</DescriptionsItem>
            <DescriptionsItem label="账号">{{
              record.data.ftpUsername
            }}</DescriptionsItem>
            <DescriptionsItem label="密码">{{
              record.data.ftpPassword
            }}</DescriptionsItem>
          </Descriptions>
        </template>
      </ProTable>
    </Modal>
  </template>
</template>

<script setup lang="tsx">
import { computed, nextTick, ref, shallowRef } from 'vue';
import {
  Descriptions,
  DescriptionsItem,
  InputPassword,
  Modal,
  message,
} from 'ant-design-vue';
import { ProForm, ProFormProps } from '@/components/ProForm';
import { ItemProps } from '@/components/ProForm/interface';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import {
  fileHistoryUpdate,
  getFileConfig,
  historyFile,
  updateFileConfig,
} from '@/api/device';
import FooterButtons from './FooterButtons.vue';

defineOptions({
  name: 'File',
});

interface Props {
  pageData: any;
  readonly?: any;
  fastConfig?: boolean;
}
const props = defineProps<Props>();
const loaded = ref(false);
const readonly = ref(props.readonly ?? true);
const formRef = shallowRef();
const formState = ref<Record<string, any>>({});
const column = 3;
const formColLayout = () => {
  const num = 24 / column;
  return { xs: num, sm: num, md: num, lg: num };
};
const formProps = computed<ProFormProps>(() => {
  return {
    labelCol: { span: 7 },
    wrapperCol: { span: 20 },
  };
});
const onValuesChange = (
  values: Record<string, any>,
  state: Record<string, any>,
) => {
  formState.value = {
    ...formState.value,
    ...state,
  };
};
const refresh = () => {
  loaded.value = false;
  nextTick(() => {
    loaded.value = true;
  });
};
const itemObj = (
  label: string,
  type: any,
  field: string,
  required: boolean = false,
  props?: any,
  layout?: any,
): ItemProps => {
  return {
    label,
    type,
    field,
    props: {
      placeholder: `请${type == 'input' ? '输入' : '选择'}${label}`,
      allowClear: false,
      autocomplete: 'off',
      ...props,
    },
    rules: [
      {
        required,
        message: `请${type == 'input' ? '输入' : '选择'}${label}`,
        trigger: 'blur',
      },
    ],
    ...layout,
  };
};
const itemRender = (title: string): ItemProps => {
  return {
    label: { title },
    type: 'input',
    field: 'h5',
    formItemRender() {
      return <h5 class='h5'>{title}</h5>;
    },
  };
};
const radioOptions = [
  { value: '0', label: '关闭' },
  { value: '1', label: '开启' },
];
const historyVisible = ref(false);

const items = computed<ProFormProps['items']>(() => [
  itemRender('服务配置'),
  itemObj('文件上传服务', 'radio', 'isOpenFileServer', true, {
    options: radioOptions,
  }),
  itemObj('上传预警文件', 'radio', 'isFileUploadWarningData', true, {
    options: radioOptions,
  }),
  itemObj('上传日志', 'radio', 'isFileUploadLogs', true, {
    options: radioOptions,
  }),
  itemObj('服务类型', 'select', 'fileServerType', true, {
    options: [
      { value: '0', label: '对象存储' },
      { value: '1', label: 'FTP服务' },
    ],
  }),
  itemObj(
    '预警文件上传延时',
    'select',
    'fileUploadTime',
    true,
    {
      options: [
        { value: '0', label: '随机' },
        { value: '1', label: '立即' },
        { value: '2', label: '2分钟' },
        { value: '5', label: '5分钟' },
        { value: '10', label: '10分钟' },
      ],
    },
    { labelCol: { span: 9 } },
  ),
  itemRender('对象存储'),
  itemObj('服务地址', 'input', 'fileServerIp', false),
  itemObj('服务端口', 'input', 'fileServerPort', true),
  itemObj('AccessKey', 'input', 'fileAccessKey', false),
  {
    label: 'SecretKey',
    type: 'input',
    field: 'fileSecretKey',
    customRender(state) {
      return (
        <InputPassword
          v-model:value={state.fileSecretKey}
          placeholder='请输入文件服务私密密钥'
          autocomplete='new-password'
        />
      );
    },
  },
  itemObj('BucketName', 'input', 'fileBucketName', false),
  itemRender('FTP服务'),
  itemObj('服务地址', 'input', 'ftpServerIp', false),
  itemObj('服务端口', 'input', 'ftpServerPort', true),
  itemObj('账号', 'input', 'ftpUsername', false),
  {
    label: '密码',
    type: 'input',
    field: 'ftpPassword',
    customRender(state) {
      return (
        <InputPassword
          v-model:value={state.ftpPassword}
          placeholder='请输入FTP密码'
          autocomplete='new-password'
        />
      );
    },
  },
]);

props.pageData.fileConfigsJson
  ? (() => {
      formState.value = JSON.parse(props.pageData.fileConfigsJson);
      loaded.value = true;
    })()
  : getFileConfig(props.pageData.code).then((res: any) => {
      formState.value = res.data;
      formState.value.code = props.pageData.code;
      loaded.value = true;
    });

const _historyFile = async (params: any) => {
  params.code = props.pageData.code;
  const res: any = await historyFile(params);
  res.rows.forEach((item: any) => {
    if (typeof item.data == 'string') {
      item.data = JSON.parse(item.data);
    }
  });
  return res;
};
const File_deploy = (record: any) => {
  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: '确定是否下发该配置?下发后会覆盖设备当前配置',
    onOk: async () => {
      const res = await fileHistoryUpdate(
        props.pageData.code + '/' + record.id,
      );
      historyVisible.value = false;
      message.success(res.msg);
    },
  });
};
const expandedRowKeys: any = ref([]);
const handleExpand = (expanded: any, record: any) => {
  if (expanded) {
    expandedRowKeys.value = [record.id];
  } else {
    expandedRowKeys.value = [];
  }
};
const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '时间',
    dataIndex: 'createTime',
    width: 120,
  },
  {
    title: '文件上传服务',
    dataIndex: ['data', 'isOpenFileServer'],
    width: 80,
    customRender({ text }) {
      return text == '1' ? '开启' : '关闭';
    },
  },
  {
    title: '上传预警文件',
    dataIndex: ['data', 'isFileUploadWarningData'],
    width: 80,
    customRender({ text }) {
      return text == '1' ? '开启' : '关闭';
    },
  },
  {
    title: '上传日志',
    dataIndex: ['data', 'isFileUploadLogs'],
    width: 80,
    customRender({ text }) {
      return text == '1' ? '开启' : '关闭';
    },
  },
  {
    title: '服务类型',
    dataIndex: ['data', 'fileServerType'],
    width: 80,
    customRender({ text }) {
      return text == '1' ? 'FTP服务' : '对象存储';
    },
  },
  {
    title: '预警文件上传延时',
    dataIndex: ['data', 'fileUploadTime'],
    width: 80,
    customRender({ text }) {
      return text == '0' ? '随机' : text == '1' ? '立即' : `${text}分钟`;
    },
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: 60,
  },
]);

defineExpose({
  async save() {
    const data = await formRef.value.validate();
    props.pageData.fileConfigsJson = JSON.stringify(data);
  },
});
</script>
